<?php
/**
 * Created by PhpStorm.
 * User: mrjnamei
 * Date: 17-5-9
 * Time: 上午11:22
 */

namespace App\Winged\Backend\Http;

use Illuminate\Support\Facades\Log;

class WingedHttp
{
    /* methods consts */
    const GET = 'GET';
    const POST = 'POST';
    const MULTIPART = 'multipart';

    protected $config;
    /**
     * @var $driver 请求的驱动　
     * @see winged.backend.php
     */
    protected $driver;

    /**
     * @var $base_uri 请求的根路由　http(s)://www.xxx.com(/)
     */
    protected $base_uri;

    /**
     * @var $request 请求体
     */
    protected $request = null;

    /**
     * @var $response 响应体
     */
    protected $response = null;

    public function __construct($channelConfig)
    {
        $this->config = $channelConfig;
        $this->createDriver();
    }

    public function request($path, $method, $body = [], $headers = [])
    {
        try {

            if(config('app.enable_db_log'))
            {
                $model = app()->make(\App\Log::class);
                $model->path = $path ;
                $model->method = $method ;
                $model->request_data = json_encode($body);
                $model->request_header = json_encode($headers);
                $time = microtime(true);
            }

            $response = $this->driver->request($path, $method, $body, $headers);

            if(config('app.enable_db_log'))
            {
                $model->request_time = microtime(true) - $time ;
                $model->response_data = json_encode($response) ;
                $model->save();
            }

            return $response ;
        } catch (\Exception $e) {
            // 发生异常时，
            Log::error('[{' . $path . '}] 请求异常：' . $e->getMessage());
            throw $e;
        }
    }

    private function response()
    {
        list($statusCode, $body) = $this->driver->response();
        Log::info(sprintf("响应：status: %s \r\n body: %s", $statusCode, $body));
        return $body;
    }

    private function createDriver()
    {
        $driverName = ucfirst($this->config['driver']);
        $klass      = "\\App\\Winged\\Backend\\Http\\Drivers\\{$driverName}";
        if (!class_exists($klass)) {
            throw new \RuntimeException(sprintf('%s 后台驱动不存在', $this->config['driver']));
        }
        $this->driver = new $klass($this->config);
    }
}